package jee.boot.module.file.attachment.service;

import jee.boot.common.basic.CrudService;
import jee.boot.common.basic.ServiceException;
import jee.boot.common.utils.FileUtils;
import jee.boot.common.utils.StringUtils;
import jee.boot.entity.file.Attachment;
import jee.boot.module.file.attachment.dao.AttachmentDao;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;


/**
 * 附件Service
 * 
 * @author zhilei.wang
 * @version 2018-01-25
 */
@Service
public class AttachmentService extends CrudService<AttachmentDao, Attachment> {

	public Attachment upload(MultipartFile file) throws IOException {
		return documentStorageClient.uploadFromMultipartFile(file);
	}

	public void delete(Attachment entity) {
		try {
			documentStorageClient.deleteFile(entity.getId());
		} catch (FileNotFoundException e) {
			throw  new ServiceException(e);
		}

	}

	public void download(HttpServletRequest request, HttpServletResponse response, Attachment entity) throws Exception {
		if (entity == null || StringUtils.isBlank(entity.getId())) {
			throw new Exception("请提供要下载的文件ID");
		}
		Attachment attachment = get(entity);
		if (attachment == null) {
			throw new Exception("附件[" + entity.getId() + "]数据不存在");
		}
		File file =documentStorageClient.downloadToFile(attachment.getId());
		if (!file.exists()) {
			throw new Exception("附件[" + entity.getId() + "]数据对应的文件[" + file.getAbsolutePath() + "]不存在");
		}
		FileUtils.downFile(file, request, response, attachment.getFileName());
	}

}